package per.chenyl.framework.persistence.test.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import per.chenyl.framework.persistence.test.entity.User;
import per.chenyl.framework.persistence.test.mapper.UserMapper;
import per.chenyl.framework.persistence.test.service.IServiceUser;
import per.chenyl.framework.persistence.wrapper.DeleteWrapper;
import per.chenyl.framework.persistence.wrapper.QueryWrapper;
import per.chenyl.framework.persistence.wrapper.UpdateWrapper;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {
    private final UserMapper userMapper;
    private final IServiceUser serviceUser;

    public UserController(UserMapper userMapper, IServiceUser serviceUser) {
        this.userMapper = userMapper;
        this.serviceUser = serviceUser;
    }

    @GetMapping("/test1")
    public List<User> getUsers() {
        return userMapper.selectAll(new QueryWrapper<>());
    }

    @GetMapping("/test2")
    public List<User> delete1() {
        userMapper.delete(new DeleteWrapper<User>().eq("id",1));
        return userMapper.selectAll(new QueryWrapper<>());
    }

    @GetMapping("/test3")
    public List<User> batcheDelete() {
        return userMapper.selectAll(new QueryWrapper<>());
    }

    @GetMapping("/test4")
    public List<User> insert() {
        List<User> u = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            User user = new User();
            user.setAge(10 - i);
            user.setName("name"+i );
            u.add(user);
        }
        long s1 = System.currentTimeMillis();
        userMapper.batchInsert(u);
        System.out.println((System.currentTimeMillis()-s1)+"batch!");

//        long s2 = System.currentTimeMillis();
//        for (int i = 0; i < u.size(); i++) {
//            userMapper.insert(u.get(i));
//        }
//        System.out.println((System.currentTimeMillis()-s2)+"fori!");


        return userMapper.selectAll(new QueryWrapper<>());
    }

    @GetMapping("/test5")
    public List<User> update() {
        List<User> u = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(i);
            user.setAge(10 - i);
            user.setName("");
            u.add(user);
        }
        long s1 = System.currentTimeMillis();
        userMapper.batchUpdate(u,new UpdateWrapper<>());
        System.out.println((System.currentTimeMillis()-s1)+"batch!");
        return userMapper.selectAll(new QueryWrapper<>());
    }

    @GetMapping("/test6")
    public String testTransaction() {
        return serviceUser.testTransaction();
    }
}
